<template>
  <div class="page-distribution-prod">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="test-form"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            :label="$t('product.prodName')+':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.prodName"
              clearable
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('product.status')+':'"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.state"
              clearable
              :placeholder="$t('product.status')"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange(true)"
            >
              {{ $t('shopFeature.searchBar.search') }}
            </div>
            <div
              class="default-btn"
              @click="clearSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 搜索栏end -->
    <!-- 表格主体 -->
    <div class="main-container">
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          :disabled="!dataList.length"
          class="all-check-btn"
          @change="handleSelectAll"
        >
          {{ $t('publics.selectAll') }}
        </el-checkbox>
        <span
          v-if="dataListSelections.length"
          class="had-selected"
        >{{ $t('publics.selected') }} {{ dataListSelections.length }}</span>
        <div
          v-if="isAuth('seckill:seckill:save')"
          class="default-btn primary-btn"
          @click="addOrUpdateHandle()"
        >
          {{ $t("crud.addTitle") }}
        </div>
        <div
          v-if="isAuth('distribution:distributionProd:delete')"
          :class="[!dataListSelections.length ? 'disabled-btn':'','default-btn']"
          @click.stop="deleteHandle"
        >
          {{ $t("sys.batchDelete") }}
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con seckill-table">
        <el-table
          ref="prodListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="selectionChange"
        >
          <el-table-column
            v-if="dataList.length"
            align="left"
            type="selection"
            width="55"
          />

          <el-table-column
            :label="$t('product.prodInfo')"
            min-width="300"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.product.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.product.prodName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            align="left"
            prop="state"
            :label="$t('product.status')"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ [$t("publics.metLowerShelf"), $t("publics.metUpperShelf"), $t("product.violation"),
                    $t("product.pendingReview")]
                  [scope.row.state] }}
              </div>
            </template>
          </el-table-column>

          <!-- 奖励比例 -->
          <el-table-column
            prop="state"
            :label="$t('marketing.rewardRatio')"
            width="150"
          >
            <template #default="scope">
              <div
                v-if="scope.row.awardProportion === 0"
                class="tag-text"
              >
                {{ $t("marketing.proporteward") }}
              </div>
              <div
                v-if="scope.row.awardProportion === 1"
                class="tag-text"
              >
                {{ $t("marketing.rewardByFixedValue") }}
              </div>
            </template>
          </el-table-column>
          <!-- 间推奖励 -->
          <el-table-column
            prop="state"
            :label="$t('marketing.inviterReward')"
          >
            <template #default="scope">
              <div
                v-if="scope.row.parentAwardSet === 0"
                class="tag-text"
              >
                {{ $t("station.close") }}
              </div>
              <div
                v-if="scope.row.parentAwardSet === 1"
                class="tag-text"
              >
                {{ $t("groups.turnOn") }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            fixed="right"
            width="240"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('distribution:distributionProd:update')"
                  class="default-btn text-btn"
                  @click="addOrUpdateHandle(scope.row)"
                >
                  {{ $t("crud.updateBtn") }}
                </div>
                <div
                  v-if="isAuth('distribution:distributionProd:delete')"
                  class="default-btn text-btn"
                  @click="deleteHandle(scope.row)"
                >
                  {{ $t("text.delBtn") }}
                </div>
                <div
                  v-if="isAuth('distribution:distributionProd:auditApply') && scope.row.state > 1"
                  class="default-btn text-btn"
                  @click="auditEventHandle(scope.row.distributionProdId)"
                >
                  {{ $t(scope.row.state === 2 ? "groups.applyForListing":"groups.moderated") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 表格主体end -->

    <!-- 下线管理弹窗-->
    <offlineEventHandle
      v-if="offlineEventHandleVisible"
      ref="offlineEventRef"
      select-url="/distribution/distributionProd/getOfflineEventByDistProdId"
      apply-url="/distribution/distributionProd/auditApply"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index.js'

const Data = reactive({
  theData: null, // 保存上次点击查询的请求条件
  theParams: null, // 保存上次点击查询的请求条件

  dataForm: {
    prodName: ''
  },
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  selectAll: null,
  searchForm: {
    prodName: null,
    state: null
  },
  statusList: [
    {
      label: $t('publics.metLowerShelf'),
      value: 0
    }, {
      label: $t('publics.metUpperShelf'),
      value: 1
    }, {
      label: $t('product.violation'),
      value: 2
    }, {
      label: $t('product.pendingReview'),
      value: 3
    }
  ],
  dataList: [],
  dataListLoading: false,
  dataListSelections: [],
  addOrUpdateVisible: false,
  offlineEventHandleVisible: false
})

const { page, selectAll, searchForm, statusList, dataList, dataListSelections, offlineEventHandleVisible } = toRefs(Data)

onMounted(() => {
  getDataList()
})

// 多选回调
const selectionChange = (val) => {
  Data.dataListSelections = val
  Data.selectAll = val.length === Data.dataList.length
}

const router = useRouter()
// 新增 / 修改
const addOrUpdateHandle = (data) => {
  router.push({
    path: '/marketing/distribution-prod/new-distribution-prod'
  })
  sessionStorage.setItem('bbcDistributionProdData', JSON.stringify(data))
}

// 点击查询
const searchChange = (newData = false) => {
  Data.page.currentPage = 1
  Data.page.pageSize = 10
  getDataList(Data.page, newData)
}

// 刷新回调
const refreshChange = () => {
  getDataList(Data.page)
}

// 获取数据列表
const getDataList = (page, newData = false) => {
  Data.dataListLoading = true

  if (newData || !Data.theData) {
    Data.theParams = JSON.parse(JSON.stringify(Data.searchForm))
    Data.theData = {
      status: Data.searchForm.status,
      current: page ? page.currentPage : Data.page.currentPage,
      size: page ? page.pageSize : Data.page.pageSize
    }
  } else {
    Data.theData.current = page ? page.currentPage : Data.page.currentPage
    Data.theData.size = page ? page.pageSize : Data.page.pageSize
  }
  http({
    url: http.adornUrl('/distribution/distributionProd/page'),
    method: 'get',
    params: http.adornParams(Object.assign(Data.theData, Data.theParams))
  }).then(({ data }) => {
    Data.page.total = data.total
    Data.page.pageSize = data.size
    Data.page.currentPage = data.current
    Data.dataList = data.records
    Data.dataListLoading = false
  })
}

// 删除
const deleteHandle = (row) => {
  const ids = row.distributionProdId ? [row.distributionProdId] : Data.dataListSelections.map(item => {
    return item.distributionProdId
  })
  if (!ids.length) {
    ElMessage.warning($t('marketing.pleaseSelectAProduct'))
    return
  }
  ElMessageBox.confirm(`${$t('sys.makeSure')}[${row.distributionProdId ? $t('text.delBtn') : $t('sys.batchDelete')}]${$t('text.menu')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/distribution/distributionProd'),
      method: 'delete',
      data: http.adornData(ids, false)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}

const offlineEventRef = ref()
// 下线管理
const auditEventHandle = (id) => {
  Data.offlineEventHandleVisible = true
  nextTick(() => {
    offlineEventRef.value.init(id)
  })
}

const prodListTableRef = ref()
/**
     * 全选按钮
     */
const handleSelectAll = () => {
  prodListTableRef.value.toggleAllSelection()
}

const clearSearch = () => {
  Data.searchForm.prodName = null
  Data.searchForm.state = null
}

// 每页数量变更
const handleSizeChange = (val) => {
  Data.page.pageSize = val
  getDataList()
}

// 页数变更
const handleCurrentChange = (val) => {
  Data.page.currentPage = val
  getDataList()
}
</script>

<style lang='scss' scoped>
.page-distribution-prod {
  .table-con {
    .table-cell-image {
      margin: 0;
      margin-right: 10px;
    }
  }
}

</style>
